package com.android.nearshop.app.activity.memdate;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.taptwo.android.widget.FlowIndicator;
import org.taptwo.android.widget.ViewFlow;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.TextView;

import com.android.nearshop.R;
import com.android.nearshop.app.activity.common.TemplateActivity;
import com.android.nearshop.app.activity.main.FilterActivity;
import com.android.nearshop.app.activity.main.MainIndexActivity;
import com.android.nearshop.app.adapter.listadapter.MemFlowViewAdapter;
import com.android.nearshop.app.widget.TitleBar;
import com.android.nearshop.app.widget.TitleBar.OnTitleClickListener;
import com.android.nearshop.business.location.MyBMapManager;
import com.android.nearshop.io.protocol.in.BannerAction.ADV_TYPE;
import com.android.nearshop.io.protocol.in.ShopDisCountListAction;
import com.android.nearshop.io.protocol.out.Area;
import com.android.nearshop.util.Constant;

/**
 * @File: MemDateActivity.java
 * @Description: 会员日界面
 * @Author: denglixia、zhaohua
 * @Date: 2012-8-21
 * @Copyright : copyrights reserved by personal 2012-2022
 */
public class MemDateActivity extends TemplateActivity implements OnClickListener 
{
    private ViewFlow viewFlow;
    private MemFlowViewAdapter flowAdapter ;
	private int mWeek = 0;
	private TextView[] mWeekViews;
	private TextView mToday;
	private int mSpecCityId = 0;
	private float mPosx;
	private int mScreenSize;
	private int[] mWeekRes = new int[]{R.string.sunday,
			R.string.monday,
			R.string.tuesday,
			R.string.wednesday,
			R.string.thursday,
			R.string.friday,
			R.string.saturday};
	
	private OnTouchListener mSlide = new OnTouchListener(){

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int action = event.getAction();
			if(MotionEvent.ACTION_DOWN == action)
			{
				mPosx = event.getRawX();
			}
			else if(MotionEvent.ACTION_UP == action || MotionEvent.ACTION_CANCEL == action)
			{
				float dt = event.getRawX() - mPosx;
				if(dt > mScreenSize/4)
				{
				    trigerNextDay(true);
				}
				else if(dt < -mScreenSize/4)
				{
				    trigerNextDay(false);
				}
			}
			return true;
		}
		
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState)
    {
    	super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_memdate);    
	    initViews();
	    loadData();
    }

	@Override
	public void onResume()
	{
		super.onResume();
//		int specCityId = MyApplication.getContext().getLocCityValue();
//		if(mSpecCityId == 0 || mSpecCityId != specCityId)
//		{
//		    mSpecCityId = specCityId;
//		    flowAdapter.setAreaId(mSpecCityId);
//			int curPos = viewFlow.getSelectedItemPosition();
//			flowAdapter.loadData(curPos);
//		}        
        viewFlow.setSelection(mWeek);
	}

	private void initViews()
	{
		mScreenSize = this.getResources().getDisplayMetrics().widthPixels;
		
		View parent = findViewById(R.id.memdate_panel);
		parent.setOnTouchListener(mSlide);
		
		mWeekViews = new TextView[7];
		mWeekViews[0] = (TextView) findViewById(R.id.sunday);
		mWeekViews[0].setOnClickListener(this);
		mWeekViews[0].setTag(0);
		mWeekViews[1] = (TextView) findViewById(R.id.monday);
		mWeekViews[1].setOnClickListener(this);
		mWeekViews[1].setTag(1);
		mWeekViews[2] = (TextView) findViewById(R.id.tuesday);
		mWeekViews[2].setOnClickListener(this);
		mWeekViews[2].setTag(2);
		mWeekViews[3] = (TextView) findViewById(R.id.wednesday);
		mWeekViews[3].setOnClickListener(this);
		mWeekViews[3].setTag(3);
		mWeekViews[4] = (TextView) findViewById(R.id.thursday);
		mWeekViews[4].setOnClickListener(this);
		mWeekViews[4].setTag(4);
		mWeekViews[5] = (TextView) findViewById(R.id.friday);
		mWeekViews[5].setOnClickListener(this);
		mWeekViews[5].setTag(5);
		mWeekViews[6] = (TextView) findViewById(R.id.saturday);
		mWeekViews[6].setOnClickListener(this);
		mWeekViews[6].setTag(6);
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		mWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
		mWeekViews[mWeek].setSelected(true);
		
		mToday = (TextView) findViewById(R.id.today);
		mToday.setText(mWeekRes[mWeek]);
		mTitleBar.setRigthText(getString(R.string.all));
		
		viewFlow = (ViewFlow) findViewById(R.id.viewflow);
		flowAdapter = new MemFlowViewAdapter(this);
		flowAdapter.setIdisplayNetErrAndRefreshView(this);
		viewFlow.setAdapter(flowAdapter, mWeek);
		viewFlow.setFlowIndicator(new FlowIndicator()
        {
            @Override
            public void onSwitched(View view, int position)
            {                
                onWeekChanged(position);
            }            
            @Override
            public void setViewFlow(ViewFlow view){}          
            @Override
            public void onScrolled(int h, int v, int oldh, int oldv){  }
        });
	}
	
    private void loadData()
    {

    	ArrayList<ShopDisCountListAction> list = new ArrayList<ShopDisCountListAction>();

        Location loc = MyBMapManager.getInstace(this).getMyGcjLoation();
        ShopDisCountListAction mShopDisCountListAction = null;

        for (int i = 0; i < 7; i++)
        {
            if (loc == null)
            {
                mShopDisCountListAction = new ShopDisCountListAction(mWeek,
                        114.070000, 22.620000);
            } else
            {
                mShopDisCountListAction = new ShopDisCountListAction(mWeek,
                        loc.getLongitude(), loc.getLatitude());
            }
            mShopDisCountListAction.setAreaId(mSpecCityId);
            mShopDisCountListAction.setWeek(i);
            
            list.add(mShopDisCountListAction);
        }

        flowAdapter.setList(list);
    }
    
    @Override
    public void onBackPressed() 
    {
    	if( getParent() instanceof MainIndexActivity)
    	{
    	    ((MainIndexActivity)getParent()).onBackPressed();
    	}
    }
    	
	@Override
	protected void setupTitleBar(TitleBar titleBar)
	{
	    titleBar.setTitle(R.string.memdate_title);
	    titleBar.setLeftImage(R.drawable.icon_shake_small_w);
	    titleBar.setLeftBg(R.drawable.red_button_bg);
	    
	    titleBar.setRigthText(R.string.all_area);
	    titleBar.setOnTitleClickListener(new OnTitleClickListener() 
	    {
	        //区域选择页面
            public void onRightClick() 
            {
            	Intent intent = new Intent(getApplicationContext(), FilterActivity.class);
            	intent.putExtra(Constant.LOCATION_ONLY, true);
            	startActivityForResult(intent, FilterActivity.CODE_REQUEST);
            }
            //返回历史记录
            public void onLeftClick() 
            {
                MainIndexActivity.gotoShake(MemDateActivity.this,mTitleBar.getLeftImgView());
            }
        },true, true);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == FilterActivity.CODE_REQUEST){
			if(resultCode == Activity.RESULT_OK)
            {
				Area area = (Area)data.getSerializableExtra(Constant.TAG_CITY);
                // 这里不做非法判断，非法就是移除了原来的条件，其实也是正确的[zhaohua]
				mSpecCityId = area == null ?  0 : area.areaId;            
				mTitleBar.setRigthText(area == null ?  getString(R.string.all) : area.areaName);
			    flowAdapter.setAreaId(mSpecCityId);
				int curPos = viewFlow.getSelectedItemPosition();
				flowAdapter.loadData(curPos);
				viewFlow.setSelection(mWeek);
            }
		}
	}

    @Override
    protected ADV_TYPE getAdvType()
    {
        // 显示广告，如果打开且这页需要显示的话
        return ADV_TYPE.SUB;
    }

	private void trigerNextDay(boolean leftToRight)
	{		
	    mWeekViews[mWeek].setSelected(false);
		if(leftToRight)
		{
		    mWeek++;
		}
		else
		{
			mWeek--;
		}
		if(mWeek > 6)
		{
			mWeek = 0;
		}
		if(mWeek < 0)
		{
			mWeek = 6;
		}		
		mWeekViews[mWeek].setSelected(true);
		mToday.setText(mWeekRes[mWeek]);
		viewFlow.setSelection(mWeek);
	}
	
	public void onWeekChanged(int week)
	{
	    flowAdapter.loadData(week);
	    for(int i =0 ;i < mWeekViews.length ; i++)
	    {	        
	        mWeekViews[i].setSelected(i == week);
	    }
	    mToday.setText(mWeekRes[week]);
	}

	@Override
	public void onClick(View arg0) 
	{
		mWeekViews[mWeek].setSelected(false);
		try
		{
		    mWeek = Integer.parseInt(arg0.getTag().toString());
		}
		catch(Exception e)
		{
			Calendar cal = Calendar.getInstance();
			cal.setTime(new Date());
			mWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
		}
		mWeekViews[mWeek].setSelected(true);
		mToday.setText(mWeekRes[mWeek]);
		viewFlow.setSelection(mWeek);
	}
}
